package com.spotme {
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.WebService;
	import mx.utils.*;

	public class API
	{
		private var ip:String;
		private var ws:WebService;
		private var authToken:String;
		public var currentSession:String;
		
		public function API(server_ip:String)
		{
			ip = server_ip;
		}

		public function setupWebService(callback:Function):void {
			ws = new WebService();
			var ipAddr:String = this.ip + ":8080";
			ws.wsdl = "http://"+ipAddr+"/spotme2-spotme2/GenericInterfaceAgentBean?wsdl";
			ws.loadWSDL();
			//ws.endpointURI = "http://"+ipAddr+"/spotme2-spotme2/GenericInterfaceAgentBean";
			ws.addEventListener("fault", faultHandler);
			ws.addEventListener("result", callback);
		}
		
		public function openVote(pSessionId:int, pQuestionId:int, pQuestion:String, pAnswers:Array, callback:Function=null):void {
			setupWebService((callback==null) ? handleOpenVote: callback);
			var pAnswersOrder:Array = new Array();
			for ( var j:String in pAnswers ) {
				pAnswersOrder.push(int(j)+1);
			}
			ws.openVote(pSessionId, pQuestionId, pQuestion, pAnswers, pAnswersOrder, authToken);
		}
		
		private function handleOpenVote(event:ResultEvent):void {
			trace(event);
		}
		
		public function closeVote(pSessionId:int, pQuestionId:int, callback:Function=null):void {
			setupWebService((callback==null) ? handleCloseVote : callback);
			ws.closeVote(pSessionId, pQuestionId, authToken);
		}
		
		private function handleCloseVote(event:ResultEvent):void {
			//this.currentSession = event.result.toString();
			trace(event.result);
		}
		
		public function getVoteDetailedResponses(pQuestionId:int, callback:Function=null):void {
			setupWebService((callback==null) ? handleGetVoteDetailedResponses : callback);
			ws.getVoteDetailedResponses(pQuestionId, authToken);
		}
		
		private function handleGetVoteDetailedResponses(event:ResultEvent):void {
			trace(event.result);
		}
		
		public function getPaxName(badgeId:String, callback:Function=null):void {
			setupWebService((callback==null) ? handleGetPaxName : callback);
			ws.getPaxName(badgeId, authToken);
		}
		
		private function handleGetPaxName(event:ResultEvent):void {
			trace(event.result);
		}
		
		public function sessionLogin(user:String, pass:String):void {
			setupWebService(handleSessionLogin);
			ws.sessionLogin(user, pass);
		}
		
		private function handleSessionLogin(event:ResultEvent):void {
			authToken = event.result.toString();
			
		}
		
		private function faultHandler(event:FaultEvent):void {
			Alert.show("Cannot connect to server");
			trace(event);
		}
	}
}
